import { Component } from '@angular/core';
import { ToastController, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { StorageService } from '../../providers/StorageService';
import { BuildService } from '../../providers/BuildService';
import { RoomService } from '../../providers/RoomService';

import { HomePage } from '../home/home';

@Component({
  selector: 'page-room',
  templateUrl: 'room.html',
  providers: [BuildService, RoomService]
})
export class RoomPage {
  roomForm: FormGroup;
  user_info: any;
  user_id: number;
  builds: any;
  room_id: number;
  page_title: string;

  constructor(
    private formBuilder: FormBuilder,
    public toastCtrl: ToastController,
    private storageService: StorageService,
    private buildService: BuildService,
    private roomService: RoomService,
    navParams: NavParams,
    private navCtrl: NavController
  ) {
    this.user_info = this.storageService.read('UserInfo');
    this.user_id = this.user_info.user_id;

    this.roomForm = this.formBuilder.group({
      'build_id': ['', [Validators.required]],
      'room_name': ['', [Validators.required]]
    });

    this.buildService.getList({'user_id': this.user_id}).then(data => {
      this.builds = data.build;
    });

    this.room_id = typeof navParams.get('room_id') === 'undefined' ? 0 : navParams.get('room_id');

    this.page_title = this.room_id ? '编辑' : '新增';

    if (this.room_id) {
      this.roomService.get({'room_id': this.room_id}).then(data => {
        this.roomForm.controls['build_id'].setValue(data.room.build_id);
        this.roomForm.controls['room_name'].setValue(data.room.room_name);
      });
    }
  }

  save(room, _event) {
    room.user_id = this.user_info.user_id;
    room.room_id = typeof this.room_id === 'undefined' ? 0 : this.room_id;

    _event.preventDefault();
    this.roomService.save(room).then(data => {
      if (data.status == 200)
      {
        this.navCtrl.push(HomePage, {listSelect: 'roomList'});
        this.storageService.write('Room', data.data);
        let toast = this.toastCtrl.create({
          message: '保存成功.',
          duration: 3000,
          position: 'top',
          showCloseButton: true,
          closeButtonText: '关闭'
        });
        toast.present();
      }
      else {
        let toast = this.toastCtrl.create({
          message: '保存失败.',
          duration: 3000,
          position: 'top',
          showCloseButton: true,
          closeButtonText: '关闭'
        });
        toast.present();
      }
    });
  }
}
